import 'dart:async';
import 'dart:convert';
import 'dart:developer';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '/utils/ftpclient.dart';
import '/models/ftpcmd.dart';
import 'package:web_socket_channel/io.dart';

class WebSocket extends StatefulWidget {

  @override
  _WebSocketState createState() => _WebSocketState();
}

class _WebSocketState extends State<WebSocket> {

  StreamSubscription? subscription;
  FtpClient? ftpClient;
  var channel = Get.arguments as IOWebSocketChannel;

  @override
  void initState() {
    super.initState();
    // 监听网络
    subscription = Connectivity().onConnectivityChanged.listen((ConnectivityResult result) {
      if (result.name != 'wifi') {
        log("noWifi");
        // Get.back();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    // 建立 ftp 连接
    void connectFTP(String ip, int port) {
      ftpClient = FtpClient();
      ftpClient!.connect(ip, port).then((isConnected) => {
        if (isConnected) {
          channel.sink.add('folder')
        } else {
          log("无法连接到 ftp 服务器")
        }
      });
    }

    // 下载文件
    void download(List<File> fileList, String dest) async {
      for (var file in fileList) {
        await ftpClient?.download(file.name, dest, (name, percent) => {
          log("name: $name, percent: $percent")
        });
      }
    }

    void handlePusherEvent(String message) {
      FtpCommand ftpCommand = FtpCommand.fromJson(json.decode(message));

      switch(ftpCommand.cmd) {
        case "ftp open":
          connectFTP(ftpCommand.body.host!, ftpCommand.body.port!);
          break;
        case "folderName":
          ftpClient?.getDest().then((dest) => {
            ftpClient?.checkDirectory(ftpCommand.body.folderName!).then((hasDirectory) => {
              if (hasDirectory) {
                download(ftpCommand.body.fileList!, dest.path)
              }
            })
          });
          break;
        default:

          break;
      }
    }

    void onDone() {
      log("onDone");
      //重试交互？
    }

    void onWebsocketError(e) {
      log("onDone");
      //重试交互？
    }

    channel.stream.listen(
      (message) => handlePusherEvent(message),
      onDone: () => onDone(),
      onError: (e) => onWebsocketError(e)
    );

    channel.sink.add('open');

    return Container(
      color: Colors.blue,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          MaterialButton(
            onPressed: () {
              Get.back();
            },
            child: const Text("停止"),
          )
        ],
      ),
    );
  }

  @override
  void dispose() {
    try {
      ftpClient?.shutdown();
      channel.sink.close();
      subscription?.cancel();
    } catch (e) {
      log(e.toString());
    }
    super.dispose();
  }
}
